package com.kobeliu.controller;

import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.enums.PaymentStatus;
import com.kobeliu.pojo.MerchantOrders;
import com.kobeliu.pojo.PreOrderResult;
import com.kobeliu.pojo.bo.MerchantOrderBO;
import com.kobeliu.resource.WxPayResource;
import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.service.PaymentOrderService;
import com.kobeliu.service.WxOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController extends BaseInfoProperties {

    @Autowired
    private PaymentOrderService paymentOrderService;

    @Autowired
    private WxPayResource wxPayResource;

    @Autowired
    private WxOrderService wxOrderService;

    @PostMapping("createMerchantOrder")
    public GraceJSONResult createMerchantOrder(@RequestBody MerchantOrderBO bo){

        String merchantOrderId = bo.getMerchantOrderId();
        String merchantUserId = bo.getMerchantUserId();
        String merchantCompanyId = bo.getMerchantCompanyId();
        Integer amount = bo.getAmount();
        Integer payMethod = bo.getPayMethod();
        String returnUrl = bo.getReturnUrl();
        String comeFrom = bo.getComeFrom();

        //判断上述的字段是否都存在 若有不存在，则失败
        if(StringUtils.isBlank(merchantCompanyId)
                || StringUtils.isBlank(merchantOrderId)
                || StringUtils.isBlank(merchantUserId)
                || StringUtils.isBlank(returnUrl)
                || StringUtils.isBlank(comeFrom)
                || amount == null
                || payMethod == null){
            return GraceJSONResult.errorMsg("缺少参数，请检查！！");
        }

        // 保存传来的商户订单信息
        boolean isSuccess = false;
        try{
            isSuccess = paymentOrderService.createPaymentOrder(bo);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.errorMsg(e.getMessage());
        }
        if(isSuccess) {
            return GraceJSONResult.ok("商户订单创建完成");
        }
        return GraceJSONResult.errorMsg("商户订单创建失败");
    }

    /**
     * 查询商户订单状态
     * @param merchantOrderId
     * @return
     */
    @PostMapping("getMerchantOrderInfo")
    public GraceJSONResult getMerchantOrderInfo(String merchantOrderId){

        if(StringUtils.isBlank(merchantOrderId)){
            return GraceJSONResult.errorMsg("查询参数不能为空");
        }

        // MerchantOrders orderInfo = paymentOrderService.queryOrderInfo(merchantOrderId,)
        return GraceJSONResult.ok();
    }

    @PostMapping("getWXPayQRCode")
    public GraceJSONResult getWXPayQRCode(@RequestBody MerchantOrderBO bo){
        String merchantOrderId = bo.getMerchantOrderId();

        if(StringUtils.isBlank(merchantOrderId)){
            return GraceJSONResult.errorMsg("查询参数不能为空");
        }

        //查询商户订单信息
        MerchantOrders waitOrder = paymentOrderService.queryOrderInfo(merchantOrderId, PaymentStatus.WAIT_PAY);

        if(waitOrder != null){
            //商品描述
            String body = waitOrder.getComeFrom() + "VIP充值 - 付款单号["+merchantOrderId+"'";
            // 商户订单号
            String out_trade_no = merchantOrderId;

            //从redis中获得这笔订单的微信支付二维码，如果订单状态没有支付就放入 防止用户频繁刷新
            String qrCodeUrl = redis.get(wxPayResource.getQrcodeKey() + ":" + merchantOrderId);
            if(StringUtils.isBlank(qrCodeUrl)){
                //订单总金额，单位为分
                String total_fee = String.valueOf(waitOrder.getAmount());

                //统一下单
                PreOrderResult result = wxOrderService.placeOrder(body,out_trade_no,total_fee);

                //像微信端发送了请求
                if(result.getReturn_code().equalsIgnoreCase("FAIL")){
                    return GraceJSONResult.errorMsg(result.getReturn_msg());
                }
                qrCodeUrl = result.getCode_url();

                redis.set(wxPayResource.getQrcodeKey() + ":" + merchantOrderId,qrCodeUrl,wxPayResource.getQrcodeExpire());

                return GraceJSONResult.ok(qrCodeUrl);
            }else {
                //如果redis中有值，则代表订单已经创建了
                return GraceJSONResult.ok(qrCodeUrl);
            }
        }
        return GraceJSONResult.errorMsg("订单出错");
    }

}
